package com.hc.commodity.dao.impl;

import com.hc.commodity.dao.DeptDao;
import com.hc.commodity.pojo.Dept;
import com.hc.commodity.utils.JdbcUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.swing.*;
import java.util.List;

/**
 * @author hs
 */
public class DeptDaoImpl implements DeptDao {

    private JdbcTemplate jdbcTemplate;

    public DeptDaoImpl() {
        jdbcTemplate = new JdbcTemplate(JdbcUtils.getDataSource());
    }

    @Override
    public List<Dept> findAll() {
        return jdbcTemplate.query("select * from dept", new BeanPropertyRowMapper<Dept>(Dept.class));
    }

    @Override
    public int findAllNumber() {
        int count = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM `dept`", Integer.class);
        return count;
    }

    @Override
    public Dept findById(int id) {
        return jdbcTemplate.queryForObject("select * from dept where deptno=?",new BeanPropertyRowMapper<Dept>(Dept.class),id);
    }

    @Override
    public void addDept(Dept dept) {
        jdbcTemplate.update("INSERT INTO dept VALUES(?,?,?)",dept.getDeptno(),dept.getDname(),dept.getLoc());
    }

    @Override
    public void delDeptById(int id) {
        jdbcTemplate.update("DELETE FROM dept WHERE deptno=?",id);
    }

    @Override
    public void updateDept(Dept dept) {
        jdbcTemplate.update("UPDATE  dept set dname=?,loc=? WHERE deptno=?",dept.getDname(),dept.getLoc(),dept.getDeptno());
    }

    @Override
    public List<Dept> findByPage(int beginPage, int pageSize) {
        List<Dept> deptList = jdbcTemplate.query("SELECT * FROM `dept` LIMIT ?,?", new BeanPropertyRowMapper<Dept>(Dept.class), beginPage, pageSize);
        return deptList;
    }
}
